﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataTramsmittingServer
{
    public class Common
    {
        /// <summary>
        /// 对象序列化
        /// </summary>
        /// <param name="msg">需要序列化的对象</param>
        /// <returns>序列化后的buffer</returns>
        public byte[] GetBytesFromProtoObject(Google.Protobuf.IMessage msg)
        {
            using (MemoryStream sndms = new MemoryStream())
            {
                Google.Protobuf.CodedOutputStream cos = new Google.Protobuf.CodedOutputStream(sndms);
                cos.WriteMessage(msg);
                cos.Flush();
                return sndms.ToArray();
            }
        }
        /// <summary>
        /// 对象反序列化
        /// </summary>
        /// <typeparam name="T">序列化的对象类型</typeparam>
        /// <param name="bytes">序列化的对象buffer</param>
        /// <returns>对象</returns>
        public T GetProtobufObjectFromBytes<T>(byte[] bytes) where T : Google.Protobuf.IMessage, new()
        {
            Google.Protobuf.CodedInputStream cis = new Google.Protobuf.CodedInputStream(bytes);
            T msg = new T();
            cis.ReadMessage(msg);
            return msg;
        }

    }
}
